﻿using Meow.Core.Utils;
using Meow.Editor.UI;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Myra;
using Myra.Graphics2D.UI;
using System;

namespace Meow.Editor;

public class Editor : Game
{
    private GraphicsDeviceManager _graphics;
    private SpriteBatch _spriteBatch;

    public Color ClearColor = new Microsoft.Xna.Framework.Color(0.3f, 0.3f, 0.3f);
    internal Desktop Desktop;

    public Editor()
    {
        _graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "";
        IsMouseVisible = true;
    }

    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    protected override void LoadContent()
    {
        _spriteBatch = new SpriteBatch(GraphicsDevice);

        //var editorLogo = Content.Load<Texture2D>("EditorAssets/editorlogo");
        //Console.Write(ImgTools.ImageToSymbol(editorLogo));

        SetBestResolution(false);

        MyraEnvironment.Game = this;
        MyraEnvironment.EnableModalDarkening = true;
        Desktop = new Desktop();

        var panel = new ModelImporter(this);
        Desktop.Root = panel;

        // TODO: use this.Content to load your game content here
    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();

        // TODO: Add your update logic here

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(ClearColor);

        Desktop.Render();
        // TODO: Add your drawing code here

        base.Draw(gameTime);
    }




    public void SetBestResolution(bool fullscreen)
    {
        var graphics = _graphics.GraphicsDevice;
        var modes = graphics.Adapter.SupportedDisplayModes;
        var width = 800;
        var height = 480;

        width = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
        height = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
        // Console.WriteLine("Base resolution as: " + width + " x " + height);

        if (!fullscreen)
        {
            width -= width / 16;
            height -= height / 12;
        }
        else
        {
            width = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
            height = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
            _graphics.HardwareModeSwitch = false;
        }

        _graphics.PreferredBackBufferWidth = width;
        _graphics.PreferredBackBufferHeight = height;

        _graphics.IsFullScreen = fullscreen;
        _graphics.ApplyChanges();

    }
}
